using B.S.RbacData.ErrorCode;
using MediatR;
using SupplierCustomerManagement.Write.API.Applications.Commands.attachments;
using SupplierCustomerManagement.Write.API.Services;
using SupplierCustomerManagement.Infrastructure;
using SupplierCustomerManagement.Domain.Entities;
using System.Linq;
using B.S.RbacData.Infrastructure;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.attachments
{
    /// <summary>
    /// 添加附件命令处理器
    /// </summary>
    public class AddAttachmentCommandHandler : IRequestHandler<AddAttachmentCommand, ApiResult<int>>
    {
        private readonly IMinioService _minioService;
        private readonly IBaseRepository<Attachment> _attachmentRepository;
        private readonly ILogger<AddAttachmentCommandHandler> _logger;

        public AddAttachmentCommandHandler(
            IMinioService minioService,
            IBaseRepository<Attachment> attachmentRepository,
            ILogger<AddAttachmentCommandHandler> logger)
        {
            _minioService = minioService;
            _attachmentRepository = attachmentRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理添加附件命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>添加结果</returns>
        public async Task<ApiResult<int>> Handle(AddAttachmentCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理附件上传命令，文件名：{FileName}，存储桶：{BucketName}",
                    request.AttachmentFile.FileName, request.BucketName);

                // 验证文件
                if (request.AttachmentFile == null || request.AttachmentFile.Length == 0)
                {
                    _logger.LogWarning("上传的文件为空或无效");
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.fails,
                        message = "上传的文件为空或无效",
                        data = 0
                    };
                }

                // 验证文件大小（默认限制为50MB）
                var maxFileSize = 50 * 1024 * 1024; // 50MB
                if (request.AttachmentFile.Length > maxFileSize)
                {
                    _logger.LogWarning("文件大小超过限制：{FileSize} bytes，最大允许：{MaxFileSize} bytes",
                        request.AttachmentFile.Length, maxFileSize);
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.fails,
                        message = $"文件大小超过限制，最大允许：{maxFileSize / 1024 / 1024}MB",
                        data = 0
                    };
                }

                // 生成对象名称
                string objectName;
                if (request.GenerateUniqueName)
                {
                    var uniqueFileName = MinioService.GenerateUniqueFileName(request.AttachmentFile.FileName);
                    objectName = $"{request.Prefix}/{uniqueFileName}";
                }
                else
                {
                    objectName = $"{request.Prefix}/{request.AttachmentFile.FileName}";
                }

                _logger.LogDebug("生成的对象名称：{ObjectName}", objectName);

                // 上传文件到MinIO
                var fileUrl = await _minioService.UploadFileAsync(request.AttachmentFile, request.BucketName, objectName);

                _logger.LogInformation("文件上传成功，访问URL：{FileUrl}", fileUrl);

                // 创建附件实体
                var attachment = new Attachment
                {
                    FileName = request.AttachmentFile.FileName,
                    OriginalFileName = request.AttachmentFile.FileName,
                    FilePath = fileUrl,
                    FileSize = request.AttachmentFile.Length,
                    FileType = Path.GetExtension(request.AttachmentFile.FileName),
                    FileExtension = Path.GetExtension(request.AttachmentFile.FileName),
                    RelatedEntityId = request.RelatedEntityId,
                    RelatedEntityType = request.RelatedEntityType,
                    UploaderId = request.UploaderId,
                    UploaderName = request.UploaderName,
                    Remarks = request.Remarks
                };

                // 保存到数据库
                await _attachmentRepository.AddAsync(attachment);
            

                _logger.LogInformation("附件信息保存成功，ID：{AttachmentId}", attachment.Id);

                return new ApiResult<int>
                {
                    code = ResultEnumCode.Ok,
                    message = "附件上传成功",
                    data = attachment.Id
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "附件上传过程中发生异常，文件名：{FileName}", request.AttachmentFile?.FileName);

                return new ApiResult<int>
                {
                    code = ResultEnumCode.fails,
                    message = $"附件上传失败：{ex.Message}",
                    data = 0
                };
            }
        }
    }
} 